import { wechatGetCpSignatureAPI } from '@/wechat/api'

import { Loading } from 'element-ui'
import { mapGetters } from 'vuex'
import Lockr from 'lockr'
// import axios from 'axios'
import { getLoginCode } from '../utils'
import { removeAuth } from '@/utils/auth'
import { resetRouter } from '@/router'

export default {
  created() {
    console.log('----------- login page created')
    this.wkValidateWxLogin()
  },
  computed: {
    ...mapGetters([
      'userInfo',
      'isWxUser'
    ])
  },
  watch: {
    $route() {
      if (this.isWxUser && Lockr.get('Admin-Token')) {
        // this.wkRegisterWxPlugin()
      }
    },

    isWxUser: {
      handler(value) {
        if (value && Lockr.get('Admin-Token')) {
          // this.wkRegisterWxPlugin()
        }
      },
      deep: true
    }
  },
  methods: {
    /**
     * 根据url验证是否微信登录
     */
    async wkValidateWxLogin() {
      const codeInfo = getLoginCode()
      const localCode = localStorage.getItem('wx_code')
      if ((codeInfo && codeInfo.cpCode != localCode)) {
        // token 可能错乱登录前先清缓存 重置路由
        localStorage.removeItem('Admin-Token')
        await removeAuth()
        resetRouter()
        localStorage.setItem('wx_code', codeInfo.cpCode)
        const loading = Loading.service({ fullscreen: true })
        this.$store
          .dispatch('Login', {
            ...codeInfo,
            type: 1
          })
          .then(res => {
            // this.wkRegisterWxPlugin()
            this.$router.push({ path: '/oa-front' })
            loading.close()
          })
          .catch(res => {
            loading.close()
          })
      }
    },

    // wkRegisterWxPlugin() {
    //   this.getSignatureInfo()
    // },

    getSignatureInfo() {
      const url = window.location.origin + window.location.pathname + window.location.search
      wechatGetCpSignatureAPI({
        url
      }).then(res => {
        this.registerWxPlugin(res.data).then(() => {
        }).catch(() => {
        })
      }).catch(() => {
      })
    },

    registerWxPlugin(config) {
      const jsApiList = [
        'onHistoryBack', // 拦截返回键
        'hideAllNonBaseMenuItem', // 隐藏所有非基础按钮
        'previewImage', // 预览图片
        'previewFile', // 预览文件
        'getLocation', // 获取地理位置
        'selectEnterpriseContact', // 选人接口
        'getNetworkType'
      ]
      console.log('wechat: ', wx, config)
      return new Promise((resolve, reject) => {
        const agentConfig = {
          corpid: config.corpid, // 必填，企业微信的corpid，必须与当前登录的企业一致
          agentid: config.agentId, // 必填，企业微信的应用id （e.g. 1000247）
          timestamp: config.timestamp, // 必填，生成签名的时间戳
          nonceStr: config.noncestr, // 必填，生成签名的随机串
          signature: config.signature, // 必填，签名，见附录-JS-SDK使用权限签名算法
          jsApiList: jsApiList, // 必填，需要使用的JS接口列表
          success: function () {
            resolve()
          },
          fail: function (error) {
            reject(error)
          }
        }

        wx.agentConfig(agentConfig)

        wx.error(error => {
          if (process.env.NODE_ENV === 'development') {
            console.error(error)
          }
        })
      })
    }
  }
}
